package com.gulimall.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;
import com.gulimall.coupon.dao.SeckillSessionDao;
import com.gulimall.coupon.entity.SeckillSessionEntity;
import com.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.gulimall.coupon.service.SeckillSessionService;
import com.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>());

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getSeckillSkuList() {
        List<SeckillSessionEntity> sessionEntities = list(new QueryWrapper<SeckillSessionEntity>().between(
                "start_time", getSeckillTime(LocalDateTime.now(), LocalTime.MIN),
                getSeckillTime(LocalDateTime.now().plus(Duration.ofDays(2)), LocalTime.MAX)));

        for (SeckillSessionEntity sessionEntity : sessionEntities) {
            List<SeckillSkuRelationEntity> skuRelationEntities =
                    seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq(
                            "promotion_session_id", sessionEntity.getId()));

            sessionEntity.setRelationEntities(skuRelationEntities);
        }
        return sessionEntities;
    }

    public String getSeckillTime(LocalDateTime localDateTime, LocalTime localTime) {
        return localDateTime.with(localTime).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}
